package com.imooc.mymall.service.impl;

import com.imooc.mymall.exception.BusinessException;
import com.imooc.mymall.exception.ErrorCodeEnum;
import com.imooc.mymall.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * <h1>本地文件上传服务实现类</h1>
 * @Author: crowsjian
 * @Date: 2020/7/16 21:52
 */
@Slf4j
@Service("fileServiceImpl")
public class FileServiceImpl implements FileService {
    /*存储空间*/
    private static final String BUCKET = "uploads";

    @Override
    public void upload(InputStream inputStream, String filename) {
        // 拼接文件的存储路劲
        String storagePath = BUCKET + "/" + filename;
        try (
                //JDK8 TWR 是不能关闭外部资源的
                InputStream innnerInputStream = inputStream;
                FileOutputStream outputStream = new FileOutputStream(new File(storagePath));
                ){
            // 拷贝缓冲区
            byte[] buffer = new byte[1024];
            // 读取文件流长度
            int len;
            while((len = innnerInputStream.read(buffer))>0){
                outputStream.write(buffer,0, len);
            }
            // 冲刷流
            outputStream.flush();
        }catch (Exception e){
            log.error("文件上传失败",e);
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_ERROR,e);
        }
    }

    @Override
    public void upload(File file) {
        try {
            upload(new FileInputStream(file),file.getName());
        }catch (Exception e){
            log.error("文件上传失败",e);
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_ERROR,e);
        }
    }
}
